<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入用户名" v-model="queryInfo.username" clearable>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-input placeholder="请输入姓名" v-model="queryInfo.name" clearable>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="queryInfo.status" clearable placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button icon="el-icon-search" @click="getUserList">搜索</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户id" prop="id" v-if="false"></el-table-column>
        <el-table-column label="用户名" prop="username" width="200px"></el-table-column>
        <el-table-column label="姓名" prop="name" width="200px"></el-table-column>
        <el-table-column label="角色" prop="role" width="150px">
          <template slot-scope="scope">
            <el-tag v-for="item in scope.row.role" :key="item.id">{{ item.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="150px">
          <template slot-scope="scope">
            <el-switch active-value="启用" inactive-value="禁用" v-model="scope.row.status"
                       @change="userStatusChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <!-- 修改密码按钮 -->
            <el-tooltip effect="dark" content="修改密码" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="updatePassword(scope.row)"></el-button>
            </el-tooltip>
            <!-- 删除用户按钮 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini"
                         @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryInfo.page" :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
<!--        <el-form-item label="邮箱" prop="email">-->
<!--          <el-input v-model="addUserForm.email" placeholder="请输入邮箱"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="电话" prop="phoneNumber">-->
<!--          <el-input v-model="addUserForm.phoneNumber" placeholder="请输入电话"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="姓名" prop="name">-->
<!--          <el-input v-model="addUserForm.name" placeholder="请输入姓名"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="性别" prop="sex">-->
<!--          <el-radio v-model="addUserForm.sex" v-for="item in sexOptions" :key="item.value"-->
<!--                    :label="item.label">{{ item.value }}-->
<!--          </el-radio>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="国籍" prop="nationality">-->
<!--          <el-input v-model="addUserForm.nationality" disabled></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="住址" prop="address">-->
<!--          <el-input v-model="addUserForm.address" placeholder="请输入住址"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="出生日期" prop="dateOfBirth">-->
<!--          <el-date-picker v-model="addUserForm.dateOfBirth" type="date" value-format="yyyy-MM-dd"-->
<!--                          placeholder="选择日期"></el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="身份证" prop="identityCard">-->
<!--          <el-input v-model="addUserForm.identityCard" placeholder="请输入身份证号"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" >
      <div>
        <p>当前的用户：{{ userInfo.name }}</p>
        <p>当前的角色：
          <el-tag v-for="item in userInfo.role" :key="item.id" closable @close="removeUserInfoRole(item.id)">
            {{ item.name }}
          </el-tag>
        </p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" @change="roleSelectChange" placeholder="请选择角色">
            <el-option v-for="item in selectedRolesList" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right">{{ item.remark }}</span>
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkPhoneNumber = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regPhoneNumber = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regPhoneNumber.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }

    // 校验身份证号
    var checkIdentityCard = (rule, value, cb) => {
      // 验证身份证号的正则表达式
      const regIdentityCard = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

      if (regIdentityCard.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的身份证号'))
    }

    // 校验密码
    var checkPassword = (rule, value, cb) => {
      // 验证身份证号的正则表达式
      const regPassword = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/

      if (regPassword.test(value)) {
        return cb()
      }

      cb(new Error('密码必须包含字母和数字，且长度在6~15个字符之间'))
    }

    return {
      queryInfo: {
        username: '',
        name: '',
        status: '',
        page: 1,
        size: 10
      },
      statusOptions: [{
        value: '启用',
        label: '启用',
      }, {
        value: '禁用',
        label: '禁用',
      }],
      sexOptions: [{
        value: '男',
        label: '男',
      }, {
        value: '女',
        label: '女',
      }],
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        phoneNumber: '',
        name: '',
        sex: '',
        nationality: '中国',
        address: '',
        dateOfBirth: '',
        identityCard: ''
      },
      addUserFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {
            min: 3,
            max: 16,
            message: '用户名的长度在3~16个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {validator: checkPassword, trigger: "blur"}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkPhoneNumber, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {
            min: 2,
            max: 14,
            message: '用户名的长度在2~14个字符之间',
            trigger: 'blur'
          }
        ],
        sex:[
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ],
        dateOfBirth: [
          {required: true, message: '请输入出生日期', trigger: 'blur'},
        ],
        identityCard: [
          {required: true, message: '请输入身份证号', trigger: 'blur'},
          {validator: checkIdentityCard, trigger: 'blur'}
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据
      rolesList: [],
      // 下拉框中的角色数组
      selectedRolesList: [],
      // 已选中的角色Id值
      selectedRoleId: '',
      // 已选中的角色对象
      selectedRole: {}
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      this.$http.post('/driver/user/list', this.queryInfo).then(res => {
        if (res.data.code === 200) {
          this.userList = res.data.data.userList
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },
    // 监听 switch 开关状态的改变
    userStatusChanged(userStatus) {
      let status
      if (userStatus.status === '启用') {
        status = '禁用'
      } else if (userStatus.status === '禁用') {
        status = '启用'
      }
      this.$http.get("/driver/user/change/status", {
        params: {
          id: userStatus.id,
          status: userStatus.status
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
        } else {
          userStatus.status = status
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        userStatus.status = status
        this.$message.error(err.message)
      })
    },
    // 监听 size 改变的事件
    handleSizeChange(size) {
      this.queryInfo.size = size
      this.getUserList()
    },
    // 监听 page 改变的事件
    handleCurrentChange(page) {
      this.queryInfo.page = page
      this.getUserList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
      this.addDialogVisible = false
    },
    // 添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(valid => {
        if (!valid) return
        this.$http.post("/driver/user/add", this.addUserForm).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.$refs.addUserFormRef.resetFields()
            this.addDialogVisible = false
            this.getUserList()
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },

    // 修改密码
    updatePassword(data) {
      this.$prompt(
        '请输入修改后的密码：',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputErrorMessage: '输入不能为空',
          inputValidator: (value) => {
            const regPassword = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/
            if (!regPassword.test(value)) {
              return '密码必须包含字母和数字，且长度在6~15个字符之间';
            }
          }
        }).then(({value}) => {
        const params = {
          "id": data.id,
          "password": value
        }
        this.$http.post("/driver/user/update/password", params).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },

    deleteUser(id) {
      this.$confirm('确定删除该用户？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get("/driver/user/delete", {
          params: {
            id: id
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getUserList()
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err.message)
        })
      })
    },

    // 为用户分配角色
    setRole(userInfo) {
      this.userInfo = {...userInfo, role: [...userInfo.role]}

      this.$http.get("/driver/role/roleAll").then(res => {
        if (res.data.code === 200) {

          // 把获取到的角色数据保存到 data 中
          this.rolesList = res.data.data

          // 初始化下拉列表
          this.selectedRolesList = [...this.rolesList]
          const roles = this.userList.filter(t => t.id === userInfo.id).pop().role;
          for (let i in roles) {
            this.selectedRolesList = this.selectedRolesList.filter(t => t.id !== roles[i].id)
          }

          this.setRoleDialogVisible = true

        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err.message)
      })
    },

    // 删除用户的角色标签
    removeUserInfoRole(id) {
      this.userInfo.role = this.userInfo.role.filter(t => t.id !== id)
      this.selectedRolesList.push(this.rolesList.filter(t => t.id === id).pop())
    },

    // 下拉列表改变时的动作
    roleSelectChange() {
      this.selectedRole = this.selectedRolesList.filter(t => t.id === this.selectedRoleId).pop()
      this.userInfo.role.push(this.selectedRole)
      this.selectedRolesList = this.selectedRolesList.filter(t => t.id !== this.selectedRoleId)
      this.selectedRoleId = ''
    },

    // 为用户分配角色
    allotRole() {
      let rolesId = []
      for (let i in this.userInfo.role) {
        rolesId.push(this.userInfo.role[i].id)
      }

      this.$http.post("/driver/userRole/allotRoles", {
        userId: this.userInfo.id,
        rolesId: rolesId
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getUserList()
          this.setRoleDialogVisible = false
        }else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    }

  },
}
</script>

<style lang="less" scoped>

.el-tag {
  margin: 7px;
}

</style>
